﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Text.RegularExpressions;

namespace EmuladorSMS
{
    public partial class Form1 : Form
    {
        Thread t1;
        int COMANDO;
        Boolean zerarConteudo;

        public Form1()
        {
            InitializeComponent();

            button2.Text = "Desconectado";
            button2.BackColor = Color.Red;
            button1.BackColor = Color.Red;

            comboBox1.Text = "COM4";


            t1 = new Thread(threadLeitura);
            t1.Priority = ThreadPriority.Lowest;
            t1.Start();

            zerarConteudo = false;
        }

        public void threadLeitura()
        {
            string conteudo = "";
            while (true)
            {
                Thread.Sleep(2);
                try
                {
                    //if (port.ReadExisting().Length > 0)
                    {
                        try
                        {
                            if (zerarConteudo)
                            {
                                conteudo = "";
                                zerarConteudo = false;
                            }

                            string buffer = FacadeSerial.Instance.obterStringPorta();
                            if (!buffer.Equals(""))
                            {

                                try
                                {
                                    textBox2.BeginInvoke((MethodInvoker)delegate
                                    {
                                        if (buffer.IndexOf(Char.ConvertFromUtf32(26)) > -1)
                                        {
                                            //MessageBox.Show(conteudo);
                                            conteudo = receberSms(conteudo);
                                        }
                                        else
                                        {
                                            conteudo += buffer.Replace(Char.ConvertFromUtf32(13), Environment.NewLine);
                                        }
                                        conteudo = analisaComando(conteudo);
                                        //conteudo = executarComando(conteudo);
                                    });
                                }
                                catch (InvalidOperationException e) {
                                    MessageBox.Show(e.Message);
                                    Environment.Exit(0);
                                }
                            }
                        }
                        catch (Exception e) {
                            //MessageBox.Show(e.Message);
                            //Environment.Exit(0);
                        }
                    }
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.Message);
                    Environment.Exit(0);
                }
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            zerarConteudo = true;
            try
            {
                if (button1.Text.Equals("Ligar"))
                {
                    FacadeSerial.Instance.enviarStringPorta("+CLIP: \"" + textBox1.Text + "\",128,,,,0");
                    FacadeSerial.Instance.enviarStringPorta(Environment.NewLine);
                    button1.Text = "...";
                    button1.BackColor = Color.Green;
                }
                else
                {
                    button1.Text = "Ligar";
                    button1.BackColor = Color.Red;
                }
            }
            catch (NotOpenConexaoException ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (FacadeSerial.Instance.isOpen())
            {
                FacadeSerial.Instance.fecharPorta();
                button2.Text = "Desconectado";
                button2.BackColor = Color.Red;
            }
            else
            {
                try
                {
                    FacadeSerial.Instance.abrirPorta(comboBox1.Text, 9600);
                    button2.Text = "Conectado";
                    button2.BackColor = Color.Green;
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
                
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            textBox2.Text = "";
        }

        private string analisaComando(string conteudo)
        {
            if (conteudo.ToUpper().IndexOf("AT+CHUP") > -1)
            {
                conteudo = finalizarChamada(conteudo);
            }
            else if (conteudo.ToUpper().IndexOf("AT+CMGS") > -1)
            {
                //COMANDO = RECEIVER_SMS;
            }

            return conteudo;
        }

        private string finalizarChamada(string conteudo)
        {
            string comando = "AT+CHUP"+Environment.NewLine;
            if (conteudo.ToUpper().IndexOf(comando) == 0)
            {
                button1.Text = "Ligar";
                button1.BackColor = Color.Red;
                textBox2.Text += "Ligação finalizada";
                textBox2.Text += Environment.NewLine;
                conteudo = conteudo.Replace(comando, "");
            }
            return conteudo;
        }

        private string receberSms(string conteudo)
        {
            try
            {
                conteudo.Replace(Char.ConvertFromUtf32(13),Environment.NewLine);
                conteudo.Replace(Char.ConvertFromUtf32(26), "");

                string linha1 = conteudo.Substring(0, conteudo.IndexOf(Environment.NewLine));
                string linha2 = conteudo.Substring(conteudo.IndexOf(Environment.NewLine), conteudo.Length - linha1.Length);

                string[] splitLinha1 = linha1.Split('"');
                string numeroDestino = "";
                if (splitLinha1.Length > 1)
                {
                    numeroDestino = splitLinha1[1];
                }

                //MessageBox.Show(linha1);
                //MessageBox.Show(linha2);
                textBox2.Text += Environment.NewLine;
                textBox2.Text += "###Recebimento SMS###";
                textBox2.Text += Environment.NewLine;
                textBox2.Text += "Número Destino: " + numeroDestino;
                textBox2.Text += Environment.NewLine;
                textBox2.Text += "Mensagem:";
                textBox2.Text += Environment.NewLine;
                textBox2.Text += hexadecimalParaString(linha2);
            }
            catch (Exception e) 
            {
                //MessageBox.Show("3: "+e.Message);
                //Environment.Exit(0);
            }
            conteudo = "";
            return conteudo;
        }

        private string hexadecimalParaString(string conteudo)
        {
            conteudo.Replace(Char.ConvertFromUtf32(13), Environment.NewLine);
            conteudo.Replace(Char.ConvertFromUtf32(26), "");

            conteudo = substituirNullHexadecimal(conteudo);

            string retorno = "";
            //string[] hexValuesSplit = Regex.Split(conteudo, "00");
            string[] hexValuesSplit = conteudo.Split(' ');
            foreach (String hex in hexValuesSplit)
            {
                if (!hex.Equals(""))
                {
                    // Convert the number expressed in base-16 to an integer.
                    int value = Convert.ToInt32(hex, 16);
                    // Get the character corresponding to the integral value.
                    string stringValue = Char.ConvertFromUtf32(value);
                    char charValue = (char)value;
                    if (value == 13 || value == 10)
                    {
                        retorno += Environment.NewLine;
                    }
                    else
                    {
                        retorno += stringValue;
                    }
                }
            }
            return retorno;
        }

        private string substituirNullHexadecimal(string conteudo)
        {
            string retorno = "";
            conteudo = conteudo.Substring(2, conteudo.Length-2);

            for (int x = 0; x < conteudo.Length-2; x += 2)
            {
                retorno += " "+conteudo.Substring(x,2);
            }
            retorno = retorno.Replace("00","");

            return retorno;
        }

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
        }

        private void button4_Click(object sender, EventArgs e)
        {
            zerarConteudo = true;
            try
            {
                string conteudo = "+CMT: \"123456\",\"98/10/01,12 :3000+00\",129,1,2,0,\"" + textBox4.Text + "\",5\"";
                conteudo += Environment.NewLine;
                conteudo += stringParaHexadecimal(textBox3.Text);
                conteudo += Environment.NewLine;
                FacadeSerial.Instance.enviarStringPorta(conteudo);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private string stringParaHexadecimal(string conteudo)
        {
            string retorno = "";
            char[] values = conteudo.ToCharArray();
            retorno += "00";
            foreach (char letter in values)
            {
                // Get the integral value of the character.
                int value = Convert.ToInt32(letter);
                // Convert the decimal value to a hexadecimal value in string form.
                string hexOutput = String.Format("{0:X}", value);
                retorno += hexOutput;
                retorno += "00";
            }
            return retorno;
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            t1.Abort();
            while (t1.IsAlive) { }
        }
    }
}
